<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="关键字" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入关键字"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-select
          v-model="queryParams.type"
          placeholder="请选择通用查询类型"
          clearable
          filterable
        >
          <el-option
            v-for="dict in sys_query_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          @click="handleAdd"
          v-hasPermi="['query:comQuery:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['query:comQuery:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['query:comQuery:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          @click="handleExport"
          v-hasPermi="['query:comQuery:export']"
          >导出</el-button
        >
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="comQueryList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" align="center" />
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="名称" align="center" prop="name" width="200" />
      <el-table-column label="关键字" align="center" prop="code" width="200" />
      <el-table-column
        label="通用查询类型"
        align="center"
        prop="type"
        :formatter="typeFormat"
        width="200"
      />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="200"
      >
        <template #default="scope">
          <el-button
            link
            @click="handleUpdate(scope.row)"
            v-hasPermi="['query:comQuery:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row)"
            v-hasPermi="['query:comQuery:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改通用查询对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="关键字" prop="code">
          <el-input v-model="form.code" placeholder="请输入关键字" />
        </el-form-item>
        <el-form-item label="sql语句" prop="customSql">
          <el-input
            v-model="form.customSql"
            type="textarea"
            placeholder="请输入内容"
          />
          <el-button type="primary" @click="handleTest(form.customSql)"
            >测试</el-button
          >
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select
            v-model="form.type"
            placeholder="请选择通用查询类型"
            clearable
            filterable
          >
            <el-option
              v-for="dict in sys_query_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="说明" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入说明"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup name="ComQuery">
import { ref, reactive, onMounted } from "vue";
import {
  listComQuery,
  getComQuery,
  delComQuery,
  addComQuery,
  updateComQuery,
  exportComQuery,
  testBizData,
  checkCode,
} from "@/api/query/comQuery";
import { ElMessage } from "element-plus";
const { proxy } = getCurrentInstance();
const { sys_query_type } = proxy.useDict("sys_query_type");
// 定义响应式数据
const loading = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const showSearch = ref(true);
const total = ref(0);
const comQueryList = ref([]);
const title = ref("");
const open = ref(false);
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: null,
  code: null,
  type: null,
});
const form = reactive({
  id: null,
  name: null,
  code: null,
  remark: null,
  customSql: null,
  type: null,
  config: null,
});
const oldCode = ref("");

const queryFormRef = ref();
const formRef = ref();

// 自定义验证规则：检查关键字是否唯一
const codeUnique = (rule, value, callback) => {
  if (value !== "") {
    if (oldCode.value === value) {
      return callback();
    }
    checkCode(value).then((res) => {
      if (res.data === "0") {
        callback(new Error("关键字重复"));
      } else {
        callback();
      }
    });
  } else {
    callback();
  }
};

const rules = reactive({
  name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
  code: [
    { required: true, message: "关键字不能为空", trigger: "blur" },
    { validator: codeUnique, trigger: "blur" },
  ],
  customSql: [{ required: true, message: "sql语句不能为空", trigger: "blur" }],
  type: [
    { required: true, message: "通用查询类型不能为空", trigger: "change" },
  ],
});

// 测试 SQL 语句
const handleTest = (sql) => {
  if (!sql) {
    ElMessage.error("SQL 语句不能为空");
    return;
  }
  testBizData({ customSql: sql }).then(() => {
    ElMessage.success("测试成功");
  });
};

// 查询列表
const getList = async () => {
  loading.value = true;
  try {
    const response = await listComQuery(queryParams);
    comQueryList.value = response.rows;
    total.value = response.total;
  } finally {
    loading.value = false;
  }
};

// 类型格式化
const typeFormat = (row, column) => {
  return proxy.selectDictLabel(sys_query_type.value, row.type);
};

// 取消按钮
const cancel = () => {
  open.value = false;
  reset();
};

// 表单重置
const reset = () => {
  Object.assign(form, {
    id: null,
    name: null,
    code: null,
    remark: null,
    customSql: null,
    type: null,
    config: null,
  });
};

// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

// 重置按钮操作
const resetQuery = () => {
  resetForm("queryFormRef");
  handleQuery();
};

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

// 新增按钮操作
const handleAdd = () => {
  reset();
  open.value = true;
  title.value = "添加通用查询";
};

// 修改按钮操作
const handleUpdate = async (row) => {
  reset();
  const id = row.id || ids.value;
  const response = await getComQuery(id);
  Object.assign(form, response.data);
  oldCode.value = form.code;
  open.value = true;
  title.value = "修改通用查询";
};

// 提交按钮
const submitForm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (form.id != null) {
          await updateComQuery(form);
          ElMessage.success("修改成功");
        } else {
          await addComQuery(form);
          ElMessage.success("新增成功");
        }
        open.value = false;
        await getList();
      } catch (error) {
        ElMessage.error("操作失败");
      }
    }
  });
};

// 删除按钮操作
const handleDelete = async (row) => {
  const idsToDelete = row.id || ids.value;
  try {
    await ElMessageBox.confirm(
      `是否确认删除通用查询编号为"${idsToDelete}"的数据项?`,
      "警告",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );
    await delComQuery(idsToDelete);
    await getList();
    ElMessage.success("删除成功");
  } catch (error) {
    // 用户取消删除或请求失败
  }
};

// 导出按钮操作
const handleExport = async () => {
  try {
    await ElMessageBox.confirm("是否确认导出所有通用查询数据项?", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
    const response = await exportComQuery(queryParams);
    download(response.msg);
  } catch (error) {
    // 用户取消导出或请求失败
  }
};

// 生命周期钩子：组件挂载时调用
onMounted(() => {
  getList();
});
</script>
<style scoped>
.app-container {
  padding: 20px;
}

.mb8 {
  margin-bottom: 8px;
}

.small-padding {
  padding: 5px;
}

.fixed-width {
  width: 100px;
}
</style>
